package com.fuluwa.domain.security.model;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;

import com.fuluwa.domain.shared.AbstractIdDomainObject;
import com.fuluwa.infra.utils.Collections3;
import com.google.common.collect.Lists;

/**
 * 用户.
 * 
 * @author calvin
 */
@Entity
@Table(name = "ss_user")
public class User extends AbstractIdDomainObject {
	public static enum StatusType {
		ENABLE, DISABLE;
	}

	@NotBlank
	@Column(unique = true)
	private String loginName;
	@NotBlank
	private String password;
	private String email;
//	private String salt;
//	@OneToOne
//	@JoinColumn(name = "user_attr_id")
//	private UserAttribute userAttribute;

	@Enumerated(EnumType.STRING)
	private StatusType status = StatusType.ENABLE;
	// @ManyToOne
	// @JoinColumn(name = "team_id")
	// private Team team;
	// 多对多定义
	@ManyToMany
	@JoinTable(name = "ss_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
	// Fecth策略定义
	@Fetch(FetchMode.SUBSELECT)
	// 集合按id排序
	@OrderBy("id ASC")
	private List<Role> roleList = Lists.newArrayList();

	private User() {
	}

	public User(Long id) {
		super(id);
	}

	public User(String loginName, String plainPassword, String email, List<Role> roleList) {//UserAttribute userAttribute,
		this.loginName = loginName;
//		this.userAttribute = userAttribute;
		this.email=email;
		if(roleList!=null)
		this.roleList = roleList;
//		this.password=entryptPassword(plainPassword);
		this.password=new Sha256Hash(plainPassword, loginName).toBase64();
	}

	/*public User(Long id, String loginName, StatusType status) {
		super(id);
		this.loginName = loginName;
		this.status = status;
	}*/
	
	
	@Transient
	// @JsonIgnore
	public String getRoleNames() {
		return Collections3.extractToString(roleList, "name", ", ");
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public String getLoginName() {
		return loginName;
	}

	public String getPassword() {
		return password;
	}

	public StatusType getStatus() {
		return status;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void updatePassword(String plainPassword) {
		this.password=new Sha256Hash(plainPassword, loginName).toBase64();
	}

	public String getEmail() {
		return email;
	}
	
	public boolean isEnabled() {
		return StatusType.ENABLE.equals(getStatus());
	}
	
}